package cn.pli.bike.service;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;

import com.framemodule.utils.CommonUtils;
import com.framemodule.utils.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;


import cn.pli.bike.BuildConfig;
import cn.pli.bike.base.CommonConstant;
import cn.pli.bike.bean.CheckUpdateBean;
import cn.pli.bike.bean.HttpResult;
import cn.pli.bike.model.UserModel;
import cn.pli.bike.model.subscribers.ProgramSubscriber;

import cn.pli.bike.utils.EventBusAction;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


//负责大文件上传  socket长链接保持
public class ConnectService extends Service {


    private Handler handler;

    private static final int CHECK_UPDATE_DOWNLOAD_APK = 5;        //检查APk更新
    private static final int DOWNLOAD_APK = 6;                        //下载APK并安装

    public static final String TYPE_CHECK_UPDATE = "cn.pli.bike.check_update";
    public static final String TYPE_DOWN_LOAD_APK = "cn.pli.bike.update";      //


    private String type;
    private int messageWhat;

    private boolean isFirstIn = true;


    private int messageKey = 0;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //首次启动时调用
    @Override
    public void onCreate() {
        super.onCreate();
        isFirstIn = true;
        initData();

    }


    private void initData() {

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case CHECK_UPDATE_DOWNLOAD_APK:
                        checkVersion();
                        break;
                    //apk
                    case DOWNLOAD_APK:
                        String url = (String) msg.obj;
                        downApk(url);
                        break;


                }
                return false;
            }
        });
    }


    //销毁时使用
    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    /**
     * 检查更新
     */
    private void checkVersion() {
        UserModel.checkUpdate(new ProgramSubscriber<HttpResult<CheckUpdateBean>>() {
            @Override
            public void onNext(HttpResult<CheckUpdateBean> checkUpdateBeanHttpResult) {
                CheckUpdateBean checkUpdateBean = checkUpdateBeanHttpResult.getData();
                CommonConstant.checkUpdateBean = checkUpdateBean;

                if (checkUpdateBean.getVersionCode() > CommonUtils.getVersionCode(ConnectService.this)) {
                    Message message = new Message();
                    message.what = EventBusAction.UPDATE_VERSION;
                    message.obj = checkUpdateBeanHttpResult.getData();
                    EventBus.getDefault().post(message);
                }
            }
        });
    }


    private void downApk(final String apkUrl) {
        Observable<File> observable = Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                try {
                    boolean interceptFlag = false;
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
                    File file = new File(CommonConstant.MEDIA_FILE_TMP);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String apkFile = UUID.randomUUID().toString() + ".apk";
                    File ApkFile = new File(CommonConstant.MEDIA_FILE_TMP, apkFile);
                    if (!ApkFile.exists()) {
                        ApkFile.createNewFile();
                    }
                    FileOutputStream fos = new FileOutputStream(ApkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];
                    int lastProgress = 0;

                    do {
                        int numread = is.read(buf);
                        count += numread;
                        int progress = (int) (((float) count / length) * 100);
                        if (progress != lastProgress) {
                            sendDownApkProgress(progress);
                            lastProgress = progress;
                            Logger.d("progress", progress + "");
                        }


                        if (numread <= 0) {
                            sendDownApkProgress(100);
                            emitter.onNext(ApkFile);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!interceptFlag);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Consumer<File> consumer = new Consumer<File>() {
            @Override
            public void accept(File file) throws Exception {
                installApk(file);
            }
        };
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(consumer);


    }


    public void sendDownApkProgress(int progress) {
        Message message = new Message();
        message.what = EventBusAction.DOWN_APK_PROGRESS;
        message.arg1 = progress;
        EventBus.getDefault().post(message);
    }


    /**
     * 安装apk
     */
    private void installApk(File saveFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", saveFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
        //停止服务
        // stopSelf();
    }

    //每次调用startservice时启动
    @Override
    public void onStart(Intent intent, int startId) {
        if (isFirstIn) {
            isFirstIn = false;
            return;
        }
        type = intent.getType();
        if (CommonUtils.isEmpty(type)) {
            return;
        }
        messageKey = intent.getIntExtra("messageKey", 0);
        switch (type) {

            //下载apk
            case TYPE_DOWN_LOAD_APK:
                handler.sendMessage(handler.obtainMessage(DOWNLOAD_APK, intent.getStringExtra("url")));
                break;
            //检查更新
            case TYPE_CHECK_UPDATE:
                handler.sendEmptyMessage(CHECK_UPDATE_DOWNLOAD_APK);
                break;
        }
    }
}
